#include "serverHead/head.h"
#include "serverHead/taskQueue.h"

int exitPipe[2];
// 注册SIGPIPE信号
void handler(int signum){
    printf("客户端异常退出\n");
    write(exitPipe[1], "1", 1);
}

int main(int argc, char* argv[])
{   
    // ./server ../conf/server.conf
    ARGS_CHECK(argc, 2);

    int fd1 = open(argv[1], O_RDONLY);
    ERROR_CHECK(fd1, -1, "open file");

    char buf[1024] = {0};
    read(fd1, buf, sizeof(buf));
    const char *pIp;
    const char *pPort;
    const char *pNum;
    pIp = strtok(buf, " ");
    pPort = strtok(NULL, " ");
    pNum = strtok(NULL, " ");

    pipe(exitPipe);
   
    if(fork() != 0){
        printf("pid = %d\n", getpid());
        close(exitPipe[0]);
        signal(SIGPIPE, handler);
        wait(NULL);
        exit(0);
    }
    close(exitPipe[1]);
   
    //tcp连接
    int sockfd;
    tcpInit(pIp, pPort, &sockfd);

    //监听
    int epfd = epoll_create(1);
    epollAdd(epfd, sockfd);
    epollAdd(epfd, exitPipe[0]);
    struct epoll_event readyset[2];
    while(1){
        int readynum = epoll_wait(epfd,readyset,2,-1);
        for(int i = 0; i < readynum; ++i){
            // 主线程只负责管理连接
            // 每个小组长线程管理一个线程池
            if(readyset[i].data.fd == sockfd){            
                createInfo* info = (createInfo*)calloc(1, sizeof(createInfo));
                info->netfd = accept(sockfd,NULL,NULL);
                info->workerNum = atoi(pNum);
                pthread_t tid;
                pthread_create(&tid, NULL, leaderThreadFunc, (void*)info);
            }
        }
    }
    return 0;
}

